/*
 * Created on Oct 21, 2003
 *
 * To change the template for this generated file go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
package org.vectrics.recruiter.struts.admin;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Set;
import java.util.TreeMap;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.vectrics.SystemException;
import org.vectrics.common.util.StringUtils;
import org.vectrics.company.Company;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.RecruitDisplayUtils;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.recruiter.job.Job;
import org.vectrics.recruiter.job.JobStatusType;
import org.vectrics.recruiter.job.JobStatusTypeApprovalSet;
import org.vectrics.recruiter.struts.JobFormBase;
import org.vectrics.struts.Request;
import org.vectrics.user.Person;

public class AdminJobForm extends JobFormBase {

	private static final long serialVersionUID = 7456760316391265623L;
	private transient static Logger log = Logger.getLogger(ConfigurationForm.class);

	public String toString() {
		StringBuffer str = new StringBuffer();
		str.append(this.getClass().getName());
		try {
			
			PropertyDescriptor[] propertyDescs = PropertyUtils.getPropertyDescriptors(this.getClass());
			for (int i = 0; i < propertyDescs.length; i++) {
				PropertyDescriptor propDesc = (PropertyDescriptor)propertyDescs[i];
				String propName = propDesc.getName();
				Method readMethod = propDesc.getReadMethod();
				if (readMethod == null) {
					log.info("No read method for property: " + propName);
				} else {
					Object propValue = PropertyUtils.getProperty(this, propName);
					if (propValue == null)
						propValue = "null";
					str.append("\r\n * " + propName + "=" + propValue.toString());
				}
			}
		} catch (Exception ex) {
			throw new SystemException("Exception displaying properties for " + this.getClass().getName(), ex);
		}
		return(str.toString());
	}
	
	public ActionErrors doValidate(ActionMapping mapping, Request request) {
		log.debug("validate() called");
		ActionErrors errors = new ActionErrors();
		if (this.wasButtonPressed(request, "cancel") == false) {
			
			if ((getTitle() == null) || (getTitle().trim().length() <= 0)) {
				errors.add("title", new ActionMessage("error.job.title.required"));			
			}		
			
			if (isBlank(this.getFunctionId())) {
				errors.add("function", new ActionMessage("error.job.function.not.selected"));			
			}
			
			if (isBlank(this.getLocationId())) {
				errors.add("location", new ActionMessage("error.job.location.not.selected"));			
			}
			
			if (isBlank(this.getPrimaryRecruiter())) {
				errors.add("primaryRecruiter", new ActionMessage("error.job.primaryRecruiter.not.selected"));			
			}
			
			if (isBlank(this.getRequester())) {
				errors.add("requester", new ActionMessage("error.job.requester.not.selected"));			
			}
			
			// Valido que el numero de empleados requerido no sea nulo o no sea cero.
			if (isBlank(this.getNumberOfPositions())){
				errors.add("numberOfPositions", new ActionMessage("error.required.numberOfPositions"));
			}else{
				if(Integer.valueOf(this.getNumberOfPositions()).equals(new Integer(0))){
					errors.add("numberOfPositions", new ActionMessage("error.job.numberOfPositions.not.zero"));
				}
			}
			
			// Valido que el numero de curriculums no sea blanco o nulo.
			if (isBlank(this.getNumberOfReceivedResumes())){
				errors.add("numberOfReceivedResumes", new ActionMessage("error.required.received.resumes"));
			}
			
		} else {
			log.debug("Cancel button was pressed, no validation performed");
		}
		

		request.setAttribute("companyId", this.getCompanyId());
		
		Job job = null;
		Company company = null;
		if (StringUtils.isNullOrBlank(this.getJobId()) == false) {
			Long jobId = new Long(this.getJobId());
			job = RecruitServiceLocator.getJobProvider().findJob(jobId);
			company = job.getCompany();
		}
		if (company == null) {
			if (StringUtils.isNullOrBlank(this.getCompanyId()) == false) {
				company = CoreServiceLocator.getCompanyService().findCompany(new Long(this.getCompanyId()));
			}
		}
		
		if ((this.wasButtonPressed(request, "cancel") == false) && (company == null)) {
			errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.job.company"));
		}
		
		if (errors.isEmpty()) {
			log.debug("validate() - no errors");
		}		
		else {
			log.debug("validate() - errors found");
		}

		attachFormObjectsToRequest(request, ThreadProperties.getPerson(), job, company, ThreadProperties.getPerson().getLocale().getJavaLocale());		
		String mappingAttr = mapping.getAttribute();
		request.setAttribute(mappingAttr, this);
		return(errors);	
	}
	
	
	/**
	 * Add needed objects to request attributes for the JSP edit form.
	 * @param request
	 * @param authPerson
	 * @param job
	 * @param company
	 * @param locale
	 */
	public static void attachFormObjectsToRequest(Request request, Person authPerson, Job job, Company company,
			Locale locale) {
	    Set hiringManagers = new HashSet(); 
	    hiringManagers.addAll(RecruitServiceLocator.getRecruitCompanyService().findHiringManagers(company));
	    if (authPerson != null) {
	    	hiringManagers.add(authPerson);
	    } else {
	    	throw new SystemException("Authorized person is null");
	    }
	    TreeMap sortedList = new TreeMap();
	    Iterator iter = hiringManagers.iterator();
	    while (iter.hasNext()) {
	    	Person person = (Person)iter.next();
	    	sortedList.put(person.getLastName() + person.getFirstName() + person.getId(), person);
	    }
		request.setSessionAttribute("hiringManagers", sortedList.values());
		
		Collection salaryTypes = RecruitServiceLocator.getJobProvider().findAllJobSalaryTypes();
		request.setSessionAttribute("jobSalaryTypes", salaryTypes);
		
		Collection payTypes = RecruitServiceLocator.getJobProvider().findAllJobPayTypes();
		request.setSessionAttribute("jobPayTypes", payTypes);
		

		
		String fromStatusCode = null;
		JobStatusType currentJobStatusType = null;
		if (job != null) {
			fromStatusCode = job.getCurrentStatus().getStatusType().getCode();
			currentJobStatusType = job.getCurrentStatus().getStatusType();
		}
		
	    Collection allJobStatusTypes = RecruitServiceLocator.getJobProvider()
	    		.findTransitionStatusTypes(company.getDomain(), job, fromStatusCode);
	    if ((job != null) && (job.getCurrentStatus() != null))
	    	allJobStatusTypes.add(job.getCurrentStatus().getStatusType());

	    Set notAuthorizedJobStatusTypes = new HashSet();
	    Set authorizedJobStatusTypes = new HashSet();
    	JobStatusTypeApprovalSet approvalSet = RecruitServiceLocator.getJobProvider().findJobStatusApprovals(company.getDomain());
	    iter = allJobStatusTypes.iterator();
	    while (iter.hasNext()) {
	    	JobStatusType jobStatusType = (JobStatusType)iter.next();
	    	if (approvalSet.canPersonTransitionTo(company, authPerson, currentJobStatusType, jobStatusType)) {
	    		authorizedJobStatusTypes.add(jobStatusType);
	    	} else {
	    		notAuthorizedJobStatusTypes.add(jobStatusType);
	    	}
	    }
	    if (authorizedJobStatusTypes.size() > 0) {
	    	
	    }
	    
		request.setSessionAttribute("jobStatusTypes", RecruitDisplayUtils.jobStatusTypesToCoded(allJobStatusTypes, locale));
		
		Collection allJobClassificationTypes = RecruitServiceLocator.getJobProvider().findAllJobClassifications(company.getDomain());
		request.setSessionAttribute("jobClassifications", RecruitDisplayUtils.jobClassificationsToCoded(allJobClassificationTypes, locale));
	}
	

}
